# @Author   : baili
# @File     : zip_utils
# @Time     : 2022/5/19 13:43
import os
import zipfile
from csr_utils import log, get_root_dir

# todo 只保留zip
class ZipUtils:

    def __init__(self, filename: str, dest_path: str):

        # 压缩包文件
        filename = filename.lower()
        suffix = filename[filename.index("."):]
        self.filename = filename if suffix in [".zip", ".rar", ".7z"] else None
        if not self.filename:
            log.warning(f"不支持的压缩包格式：{filename}")

        # 解压目录
        self.dest_path = dest_path
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)

    def unzip_zip(self):
        """
        解压zip压缩包
        """
        if not self.filename:
            return False

        log.debug("正在解压zip压缩包...")
        try:
            with zipfile.ZipFile(self.filename, 'r') as z:
                z.extractall(self.dest_path)
        except Exception as e:
            log.error(e)

        return True

    def unzip_rar(self):
        """
        解压zip压缩包
        注意：服务端需要另外安装rar工具
        """
        if not self.filename:
            return False

        log.debug("正在解压rar压缩包")
        try:
            full_path = os.sep.join([self.dest_path, self.filename])
            cmd_str = f"unrar e {full_path}"
            os.system(command=cmd_str)
        except Exception as e:
            log.error(e)

        return True


if __name__ == '__main__':
    z = ZipUtils("demo.rar", os.sep.join([get_root_dir(), "cus_ws/abc"]))
    print(z.filename, z.dest_path)

    z.unzip_zip()
